
auto.waitFor();
requestScreenCapture();

const MAP = {
   'Home': [305, 1821],
   'BlessLand': [358, 1146],
   //'Explore' : [918, 1530],
   'Pick' :[530,1422],
   'Back' :[970,177],
   'Peach3': "peach3.png",
   'Peach4': "peach4.png",
   'Peach5': "peach5.png",
   'Peal4': "Peal4.png",
   'Peal5': "Peal5.png",
   'Water3': "water3.png",
   'Water4': "water4.png",
   'Water5': "water5.png",
   'Jade5': "jade5.png",
   'Close': "close.png",
   'LootClose': "lootclose.png",
   'Back': "back.png",
   'Explore': "explore.png",
   'Nofreerat': "nofreerat.png",
   'LootFinish': "LootFinish.png",
   'ClickToClose': "clicktoclose.png",
   'RefreshEnabled': "refreshenabled.png",
   'CheckMouse': "checkmouse.png",
   'Recall': "recall.png",
   'FirstGo':[870, 440],
   'SecondGo':[870, 667],
   'ThirdGo':[870, 895],
   'Refresh':[950, 1645],
   'ReduceTime1': [863, 1687],
   'ReduceTime2': [350,1572],
   'GetForFree': "getforfree.png",
   'CloseReduceTime': [1000, 270],
   'Me': "me.png",
   'QiangDuo': "qiangduo.png",

}

const offset = 30;
stillpeach = false;
matchingthreshold = 0.938;
refrehscount = 0;
collectcount = 0;
const currentHour = addHours(new Date(), 14).getHours();
lastCallTime = Date.now();

function handleClick (arr) {
    click(arr[0], arr[1])
    sleep(random(2000, 3000))
  }

// util 获取对应图片坐标
function getPoints (url) {
    const img = captureScreen();
    const temp = images.read(url);
    const res = images.matchTemplate(img, temp, {
        threshold: matchingthreshold, max: 6
    });
    //console.log(res);
    if (res && res.matches.length > 0) {
      const points = res.matches.map(item => [item.point.x, item.point.y].toString())
        .filter((item, index, arr) => arr.indexOf(item) === index)
        .map(item => item.split(',').map(_item => Number(_item) + 10))
       console.log(points);
       temp.recycle();
       return points
      
    }
    temp.recycle();
    return []
  }



function CollectPeach (peachPoint) {
    // 按钮距离图片y30
    console.log(peachPoint[0] + offset);
    console.log(peachPoint[1] + offset);
    handleClick([peachPoint[0] + offset, peachPoint[1] + offset]);
    point = getPoints(MAP['Recall']);
    qiang = getPoints(MAP['QiangDuo']);
    if(point.length === 0 && qiang.length === 0) {
      checkmouse =  getPoints(MAP['CheckMouse'])
      if(checkmouse.length === 0 ) {
        console.log("collect peach");
        handleClick(MAP['Pick']);
      }
      else {
        stillpeach = true;
        console.log("no mouse available close");
        Close();
      }
   
    } 
    else if (point.length > 0) {
      console.log("recall close");
      Close();
    }
    else {      
      console.log("no peach close");
      Close();
    }
    
}

function Close(){
  point = getPoints(MAP['Close'])
  if(point.length === 0) {
    console.log("There is no window to close");
    return false;
  } else {
    handleClick(point[0], point[1]);
    return true;
  }
}

function LootClose(){
  point = getPoints(MAP['LootClose'])
  if(point.length === 0) {
    console.log("There is no window to close");
    return false;
  } else {
    handleClick(point[0], point[1]);
    return true;
  }
}


function Back(){
  point = getPoints(MAP['Back']);
  if(point.length === 0) {
    console.log("There is no window to go back");
    return false;
  } else {
    handleClick(point[0], point[1]);
    return true;
  }
}

function ClickToClose(){  
  sleep(random(4000, 6000));
  point = getPoints(MAP['ClickToClose'])
  if(point.length === 0) {
    console.log("There is no window to Click To Close");
    return false;
  } else {
    handleClick(point[0], point[1]);
    return true;
  }

}

function GoToExplore()
{
  const exploreoffset = 80;
  point = getPoints(MAP['Explore']);
  if(point.length === 0) {
    console.log("There is no window to go explore");
  } 
  else {
    point[0][0] = point[0][0]+exploreoffset;
    point[0][1] = point[0][1]+exploreoffset;
    handleClick(point[0]);
  }
}

function GoToPeach()
{
  handleClick(MAP['Home']);
  handleClick(MAP['BlessLand']);
  sleep(random(3000, 4000));
  while(ConfirmLootFinish())
  {
    // The loop will continue as long as there is loot finish button
  }

  while(CheckFreeRat()== false)
  {
    console.log("There is no free rat sleep 1 minutes and check again");
    sleep( random(50, 60) * 1000);
  }
  
  while(ConfirmLootFinish())
  {
    // The loop will continue as long as there is loot finish button
  }
  stillpeach = false;
  GoToExplore();

}

function Loot(lootPoint)
{


  me =  getPoints(MAP['Me'])

  if (me.length > 0) {
    console.log("mouse already collecting");
   
  }
  else
  {
    handleClick(lootPoint);
    matchingthreshold = 0.938;
    var p5 = Collect(MAP['Peach5']);
    var p4 = Collect(MAP['Peach4']);

    matchingthreshold = 0.95;
    if(collectcount <= 80)
    {
      var w5 = Collect(MAP['Water5']);
      var w4 = Collect(MAP['Water4']);
    }
    var j5 = Collect(MAP['Jade5']);
    var p3 = Collect(MAP['Peach3']);
   
  }

  LootClose();


}

function Collect(item)
{
  point = getPoints(item);
  
  if(point.length === 0) {
    console.log("There is no " + item + " to loot");
    return false;
  } 
  else {
    console.log("loot found" + item);
    CollectPeach(point[0]);
    collectcount++;
    console.log("Collect count: " + collectcount);
    return true;
  }

}

function CheckFreeRat()
{
  point = getPoints(MAP['Nofreerat']);
  if(point.length === 0) {
    console.log("There is free rat");
    return true;
  } 
  else {
    console.log("There is no free rat");
    return false;
  }

}

function ConfirmLootFinish()
{
  point = getPoints(MAP['LootFinish']);
  if(point.length === 0) {
    console.log("There is no window to confirm loot finish");
  } 
  else {
    handleClick([515,1100]);
  }

}

function CheckRefreshEnabled()
{
  const screen = captureScreen();
  var color = images.pixel(screen, 922, 1663);
  console.log(colors.toString(color));

  if(colors.toString(color) == "#ffffefc6") {
    console.log("Refresh enabled");
    return true;

  } 
  else {
    console.log("Wait for refresh");
    return false;
  }

}

function ClickReduceTime()
{
  handleClick(MAP['ReduceTime1']);
  sleep(random(2000, 3000));
  handleClick(MAP['ReduceTime2']);
  sleep(random(2000, 3000));
  point = getPoints(MAP['GetForFree']);
  if(point.length === 0) {
    console.log("There is no reduce time");
  } else {
    point[0][0] = point[0][0]+offset;
    point[0][1] = point[0][1]+offset;
    handleClick(point[0], point[1]);
    console.log("click reduce time");
  }
  sleep(random(2000, 3000));
  handleClick(MAP['CloseReduceTime']);
  sleep(random(2000, 3000));
}



function start() {


  while(Close()) {
    // The loop will continue as long as there is close button
  }

  while(Back()) {
    // The loop will continue as long as there is back button
  }

  while(ClickToClose())
  {
    // The loop will continue as long as there is click to close button
  }

  const now = new Date();
  now.setHours(now.getHours() + 1);

  if (now - lastCallTime >= 30 * 60 * 1000) {
    ClickReduceTime();
    lastCallTime = now;
  }

  GoToPeach();


  Loot(MAP['FirstGo']);
  Loot(MAP['SecondGo']);
  Loot(MAP['ThirdGo']);

  if(CheckRefreshEnabled() == true && stillpeach == false)
  {
    handleClick(MAP['Refresh']);
    refrehscount++;
   
  }
  else if (stillpeach == true)
  {
    // go to next round
  }
  else
  {
    sleep( random(1,2) * 60 * 1000);
  }
  
  
  console.log("total Refresh time: " + refrehscount);
  console.log("total Collect time: " + collectcount);

}

function addHours(date, hours) {
  const hoursToAdd = hours * 60 * 60 * 1000;
  date.setTime(date.getTime() + hoursToAdd);
  return date;
}

(() => {
  while(true)
  {
    start();
    // cons  ole.log("Current Hour: " + currentHour);

    // if ((currentHour >= 1 && currentHour < 7) || (currentHour >= 15 && currentHour < 19)) {
    //     start();
    // } else {
    //     console.log("Waiting until 1 AM to start...");
    //     sleep(10 * 60 * 1000); // Sleep for 1 hour
    // }
  }

   
})();